package com.fkdx.interceptor;

import com.fkdx.dao.condition.TableCondition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.fkdx.common.annotation.TableAlias;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * @author: create by wsh
 * @date:2022/5/4
 */
@Aspect
@Log4j2
@Component
public class MybatisPageAspect {

    private String created = "created";

    /**
     * 启用分页实现类
     *
     * @param point 切入点
     * @return 切入点的执行结果
     * @throws Throwable 可能出现的异常
     */
    @Around("execution(public * com.fkdx.dao.mapper..*(..))")
    public Object doPaging(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        if(args != null && args.length > 0) {
            //获取第一个参数
            Object obj = args[0];
            //仅仅当第一个参数为PageBean的时候才执行分页
            if (obj instanceof TableCondition) {
                TableCondition pageBean = (TableCondition) obj;
                if (pageBean.isInitiate()) {
                    if (pageBean.getOffset() == null || pageBean.getOffset() <= 0) {
                        pageBean.setOffset(1);
                    }
                    if (pageBean.getLimit() == null) {
                        pageBean.setLimit(10);
                    }
                    log.info("启动分页方法，当前分页页号为:{},页大小:{}", pageBean.getOffset(), pageBean.getLimit());
                    Page<Object> page = PageHelper.startPage(pageBean.getOffset(), pageBean.getLimit());
                    if (StringUtils.isNoneBlank(pageBean.getOrder(), pageBean.getSort())) {
                        page.setOrderBy(pageBean.getSort() + " " + pageBean.getOrder());
                    } else {
                        Signature signature = point.getSignature();
                        MethodSignature methodSignature = (MethodSignature) signature;
                        Method method = methodSignature.getMethod();
                        if (method != null) {
                            String alias = "";
                            TableAlias t = method.getAnnotation(TableAlias.class);
                            if (t != null) {
                                if (!t.notSort()) {
                                    alias = t.name() + ".";
                                    page.setOrderBy(alias + created + " desc");
                                }
                            } else {
                                page.setOrderBy(alias + created + " desc");
                            }

                        }

                    }
                }
            }
        }

        return point.proceed(args);
    }

}
